package com.demo;

import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.IntPredicate;

/**
 * @author gxd
 * @since 2025/5/27
 */
public class LambdaTest {
    public static void main(String[] args) {
        // lambda表达式：对某些匿名内部类的写法进行简化
        // 核心：快捷键：alt + 回车
        // 示例一：
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("我是一个线程");
            }
        }).start();

        new Thread(() -> System.out.println("我是一个线程")).start();

        // 示例二：
        System.out.println(calculateNum(new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left + right;
            }
        }));

        System.out.println(calculateNum((left, right) -> left + right));

        // 示例三
        printNum(new IntPredicate() {
            @Override
            public boolean test(int value) {
                return value % 2 == 0;
            }
        });

        printNum(value -> value % 2 == 0);

        // 示例四
        System.out.println(typeConver(new Function<String, Integer>() {
            @Override
            public Integer apply(String s) {
                return Integer.valueOf(s);
            }
        }));

        System.out.println(typeConver((Function<String, Integer>) s -> Integer.valueOf(s)));

        // 示例五
        ForeachArr(new IntConsumer() {
            @Override
            public void accept(int value) {
                System.out.println(value);
            }
        });

        ForeachArr(value -> System.out.println(value));
    }

    public static int calculateNum(IntBinaryOperator operator) {
        int a = 10;
        int b = 20;
        return operator.applyAsInt(a, b);
    }

    public static void printNum(IntPredicate predicate) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            if (predicate.test(i)) {
                System.out.println(i);
            }
        }
    }

    public static <R> R typeConver(Function<String, R> function) {
        String str = "1235";
        R result = function.apply(str);
        return result;
    }

    public static void ForeachArr(IntConsumer consumer) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10};
        for (int i : arr) {
            consumer.accept(i);
        }
    }
}
